package com.zhierxi.hello.thread;


public class TestSynchronized {

    public static void main(String[] args) {
        Account account = new Account("123","456",500);
        Husband h = new Husband(account);
        Wife w = new Wife(account);

        Thread t1 = new Thread(h);
        Thread t2 = new Thread(w);
        t1.start();
        t2.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(String.format("真正余额剩余：%s",account.getBalance()));

    }
}

class Husband implements Runnable{
    private Account account;

    public Husband(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        try {
            synchronized (account){
                account.widthdraw(account.getCardno(),account.getPassword(),300);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Wife implements Runnable{
    private Account account;

    public Wife(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        try {
            synchronized(account) {
                account.widthdraw(account.getCardno(), account.getPassword(), 300);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


class Account{

    private String cardno;
    private String password;
    private double balance;

    Account(String cardno, String password, double balance) {
        this.cardno = cardno;
        this.password = password;
        this.balance = balance;
    }

    public String getCardno() {
        return cardno;
    }

    public void setCardno(String cardno) {
        this.cardno = cardno;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public void widthdraw(String no , String pwd, double ba) throws InterruptedException {
        System.out.println("请稍候。。。。");
        if(cardno.equals(no)&&password.equals(pwd)){
            System.out.println("验证通过！");
            if(ba<balance){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                balance = balance -ba;
                System.out.println(String.format("取款成功，余额为：%s",balance));
            }
            else {
                System.out.println("余额不足！");
            }
        }
        else{
            System.out.println("用户名或密码错误！");
        }
    }
}
